package com.franklin.java.api.ui.jpanel.color;


import com.intellij.openapi.util.NlsContexts;
import com.intellij.ui.ColorChooser;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBPanel;
import com.intellij.util.ui.FormBuilder;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.util.Optional;

/**
 * 颜色选择器
 * @author Franklin
 * @since 2021/9/2 17:52
 */
public class ColorSelector extends JBPanel<ColorSelector> {

    private String title;
    private JPanel colorPreview;
    private JButton chooseColorButton;


    public ColorSelector(String title,@NotNull Color originColor) {

        colorPreview = FormBuilder.createFormBuilder()
            .getPanel();
        Dimension preferredSize = new Dimension(40, 20);
        colorPreview.setPreferredSize(preferredSize);

        colorPreview.setBackground(originColor);

        chooseColorButton = new JButton("choose color");
        chooseColorButton.addActionListener(e -> {
            // 显示颜色选取器对话框, 返回选取的颜色（线程将被阻塞, 直到对话框被关闭）
//            Color color = JColorChooser.showDialog(this, "选取颜色", null);
            Color colorSelected = ColorChooser.chooseColor(this, "选取颜色", originColor);

            Optional.ofNullable(colorSelected)
                // 把选取的颜色设置为标签的背景
                .ifPresent(colorPreview::setBackground);

        });

        this.add(new JBLabel(title),0);
        this.add(new JBLabel(" Current color : "),1);
        this.add(colorPreview,2);
        this.add(chooseColorButton,3);

    }

    public Color getColor(){
        return colorPreview.getBackground();
    }
}
